package com.cgsd.heyu.widgets.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.library.utils.FileUtils;
import com.android.library.utils.SharedPreferencesHelper;
import com.android.library.utils.SystemUtil;
import com.android.library.utils.ToastHelper;
import com.cgsd.heyu.App;
import com.cgsd.heyu.R;
import com.cgsd.heyu.common.AppMobclickAgent;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.down.DownLoadListener;
import com.cgsd.heyu.down.DownLoadUtil;
import com.cgsd.heyu.entity.AppUpdateEntity;
import com.cgsd.heyu.utils.SaveFileUtil;


/**
 * @author xiaoxing
 *  下载任务弹窗
 */

public class AppUpdateDialog extends Dialog implements View.OnClickListener, DownLoadListener {
    private Context mContext;
    private TextView tvTitle;
    private TextView tvProgress;
    private LinearLayout layoutButton;
    private View viewLine;
    private TextView tvCancel;
    private AppUpdateEntity appUpdateEntity;
    private DownLoadUtil downLoadUtil;
    private String saveFile;
    private boolean isDownSuccess;

    public AppUpdateDialog(Context context, AppUpdateEntity appUpdateEntity) {
        super(context, R.style.dialog_custom);
        this.mContext = context;
        this.appUpdateEntity = appUpdateEntity;
        setContentView(R.layout.dialog_app_update);
        Window window = this.getWindow();
        if (window != null) {
            window.setGravity(Gravity.CENTER);
        }
        init();
    }


    private void init() {
        tvTitle = findViewById(R.id.tv_title);
        tvProgress = findViewById(R.id.tv_progress);
        layoutButton = findViewById(R.id.layout_button);
        viewLine = findViewById(R.id.view_line);
        tvCancel = findViewById(R.id.tv_cancel);

        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = mContext.getResources().getDisplayMetrics();
        lp.width = (int) (d.widthPixels * 0.8);
        dialogWindow.setAttributes(lp);


        tvCancel.setOnClickListener(this);
        findViewById(R.id.tv_confirm).setOnClickListener(this);
        tvProgress.setOnClickListener(this);
        initData();

    }

    private void initData() {
        if (appUpdateEntity == null) {
            return;
        }
        tvTitle.setText(appUpdateEntity.replaceContext.replace("\\n","\n"));
        downLoadUtil = new DownLoadUtil(this);

        if (getAppUpdate() == 2){
            //强制更新
            OnKeyListener keyListener = new DialogInterface.OnKeyListener(){
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode== KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0) {
                        ((Activity)mContext).finish();
                        return true;
                    } else{
                        return false;
                    }
                }
            };
            viewLine.setVisibility(View.GONE);
            setOnKeyListener(keyListener);
            setCanceledOnTouchOutside(false);
            tvCancel.setVisibility(View.GONE);
            setSaveFile();
            show();
        }else if (getAppUpdate() == 1){
            setCanceledOnTouchOutside(true);
            tvCancel.setVisibility(View.VISIBLE);
            setSaveFile();
            show();
        }

        boolean isNewVersion;
        if (getAppUpdate() > 0){
            isNewVersion = true;
        }else {
            isNewVersion = false;
        }
        SharedPreferencesHelper.put(Constants.ShareKeyValue.IS_NEW_VERSION,isNewVersion);
    }

    @Override
    public void show() {
        super.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_cancel:
                dismiss();
                break;
            case R.id.tv_confirm:
                AppMobclickAgent.onEvent(AppMobclickAgent.GENGXIN_GENGXIN);
                layoutButton.setVisibility(View.GONE);
                tvProgress.setVisibility(View.VISIBLE);
                downLoadUtil.download(appUpdateEntity.replaceUrl,saveFile);
                break;
            case R.id.tv_progress:
                if (isDownSuccess){
                    SaveFileUtil.installApk(saveFile, mContext);
                }
                break;
            default:
        }
    }



    @SuppressLint("SetTextI18n")
    @Override
    public void onProgress(long totalSize, long currentSize) {
        tvProgress.setText(currentSize*100/totalSize + "%" );
    }

    @Override
    public void onSuccess(String filePath) {
        isDownSuccess = true;
        tvProgress.setText("点击安装");
        SaveFileUtil.installApk(filePath, mContext);
    }

    @Override
    public void onFailed() {
        ToastHelper.showDefaultToast("更新下载失败，请退出重试");
    }

    /**
     * 判断升级
     * @return 0 不升级，1 推荐更新，2强制升级
     */
    private int getAppUpdate(){
        String currentVersion = SystemUtil.getVerName(mContext);
        if (appUpdateEntity.newVersion.equals(appUpdateEntity.coerceVersion) ){
            //最小升级版本和最新版本相同
            if (SystemUtil.compareVersionName(currentVersion,appUpdateEntity.newVersion) == -1){
                //app当前版本小于最新版本，则强制升级
                return 2;
            }else {
                return 0;
            }
        }else {
            if (SystemUtil.compareVersionName(currentVersion,appUpdateEntity.coerceVersion) == -1){
                //app当前版本小于最小需求版本，则强制升级
                return 2;
            }else if (SystemUtil.compareVersionName(currentVersion,appUpdateEntity.newVersion) == -1){
                //app当前版本小于最新版本，推荐更新
                return 1;
            }else {
                return 0;
            }
        }
    }

    /**
     * 设置保存app下载路径
     */
    private void setSaveFile(){
        saveFile = FileUtils.getAppPath(App.getInstance())+"app_"+SystemUtil.getVerName(App.getInstance())+".apk";
        //如果存在，则删除
//        FileUtils.deleteFile(saveFile);
    }
}
